package lucky.xiong.煞笔面试题.JUC.threadLocal.线程的父子传递;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * ThreadLocal  vs InheritableThreadLocal vs TransmittableThreadLocal
 *
 * TransmittableThreadLocal 需要引入阿里依赖。
 * @author XiongJianLin
 * @date Created in 2024/12/3 16:46
 */
public class ThreadLocal的其他类 {


    // main方法是主线程
    public static void main(String[] args) throws InterruptedException {
//        m1();
//        m2();
        m3();
    }

    /**
     * 继承线程在线程池场景不好用
     */
    private static void m3() throws InterruptedException {
        // threadLocal 只能获取当前线程数据
        InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
        threadLocal.set(Thread.currentThread().getName()+ " -- Java");
        System.out.println("threadLocal: " + threadLocal.get());

        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(()->{
            System.out.println("线程池第一次获取 main 的 threadLocal: " + threadLocal.get());
        });
        Thread.sleep(1000);

        threadLocal.set("main线程变更数据了");
        System.out.println("main线程变更数据了");

        System.out.println("main线程再次获取 threadLocal: " + threadLocal.get());

        executorService.execute(()->{
            System.out.println("线程池第二次获取 main 的 threadLocal: " + threadLocal.get());
        });

        executorService.shutdown();
    }

    /**
     * 继承线程，子线程可以获取父线程的数据
     *
     * 用于全局数据共享。
     */
    private static void m2() {
        // threadLocal 只能获取当前线程数据
        InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
        threadLocal.set(Thread.currentThread().getName()+ " -- Java");
        System.out.println("threadLocal: " + threadLocal.get());

        new Thread(()->{
            System.out.println("main方法的 threadLocal: " + threadLocal.get());
        }).start();
    }

    private static void m1() {
        // threadLocal 只能获取当前线程数据
        ThreadLocal<String> threadLocal = ThreadLocal.withInitial(()->null);
        threadLocal.set(Thread.currentThread().getName()+ " -- Java");
        System.out.println("threadLocal: " + threadLocal.get());

        new Thread(()->{
            System.out.println("main方法的 threadLocal: " + threadLocal.get());
        }).start();
    }
}
